#include "sharedmemory.hpp"
#include <signal.h>
#include <sys/wait.h>

int main()
{
    signal(17, SIG_IGN);
    My_Shared_Memory::SharedMemory myshm(FIFO_NAME, 3000, IPC_CREAT);
    char *myarr = (char *)myshm.Get();

    int *server = (int *)myarr;
    char *serverfile = myarr + 4;

    int *client = (int *)(myarr + 100);
    char *clientfile = myarr + 104;
    pid_t pid = fork();
    if (pid == 0)
    {
        while (1)
        {
            // 触发传输
            if (*server != 0)
            {
                if (strcmp(clientfile, "close") == 0 || strcmp(serverfile, "close") == 0)
                {
                    std::cout << serverfile << std::endl;
                    break;
                }
                else
                {
                    std::cout << serverfile << std::endl;
                }
                *server = 0;
            }
        }
        *server = 0;
        std::cout << "child end pid: " << getpid() << std::endl;
        std::cout << "server close" << std::endl;

        exit(0);
    }
    else if (pid > 0)
    {
        // std::cout << "client ->";
        while (1)
        {
            scanf("%s", clientfile);
            *client = 1;
            if (strcmp(clientfile, "close") == 0 || strcmp(serverfile, "close") == 0)
            {
                break;
            }
        }

        // std::cout << "parent end pid: " << getpid() << std::endl;
        std::cout << "client close" << std::endl;
    }

    return 0;
}
